package mgodb

import (
	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"time"
)

// cSpecialVisit 存储内容:企业和门禁设备的对应关系
const cSpecialVisit = "oper_special_visit"

// SVisitDB 特殊来访管理
type SVisitDB struct {
	DB *mongo.DB
}

// Init 初始化
func (a *SVisitDB) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cSpecialVisit, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"record_id", "cancel"},
			Unique: true,
		})
		return nil
	})

	var val model.ISVisit = a
	g.Provide(&inject.Object{Value: val, Name: "ISVisit"})
}

// QVisitPage 列表查询
func (a *SVisitDB) QVisitPage(params *schema.SVQParams, currentPage, pageSize uint) (int, []*schema.SVBson, error) {
	query := bson.M{
		"cancel":              0,
		"personnel_name":      bson.M{"$regex": params.PersonnelName},
		"contract_tel":        bson.M{"$regex": params.ContractTel},
		"from_enterprise":     bson.M{"$regex": params.FromEnterprise},
		"visiting_enterprise": bson.M{"$regex": params.VisitingEnterprise},
		"main_content":        bson.M{"$regex": params.MainContent},
	}
	if params.PersonnelTotal != 0 {
		query["personnel_total"] = params.PersonnelTotal
	}
	if params.StartTime != 0 {
		query["start_time"] = bson.M{"$gte": params.StartTime}
	}
	if params.StartTime != 0 {
		query["end_time"] = bson.M{"$lte": params.EndTime}
	}
	total := 0
	var err error
	items := make([]*schema.SVBson, 0)
	err = a.DB.C(cSpecialVisit, func(c *mgo.Collection) error {
		total, err = c.Find(query).Count()
		if err != nil {
			return err
		}

		return c.Find(query).Sort("-created").Skip(int((currentPage - 1) * pageSize)).Limit(int(pageSize)).All(&items)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return total, items, nil
}

// AddVisit 创建来访
func (a *SVisitDB) AddVisit(item *schema.SVBson) error {
	//创建新的条目
	err := a.DB.C(cSpecialVisit, func(c *mgo.Collection) error {
		id, err := a.DB.IncrID(cSpecialVisit)
		if err != nil {
			return err
		}
		item.ID = id
		return c.Insert(item)
	})
	if err != nil {
		return errors.Wrapf(err, "创建特殊来访错误")
	}
	return nil
}

// QVisitDetail 来访详情
func (a *SVisitDB) QVisitDetail(itemID string) (*schema.SVBson, error) {
	item := new(schema.SVBson)
	err := a.DB.C(cSpecialVisit, func(c *mgo.Collection) error {
		return c.Find(bson.M{"record_id": itemID, "cancel": 0}).One(item)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "查询特殊来访详情错误")
	}
	return item, nil
}

// Cancel 作废取消
func (a *SVisitDB) Cancel(recordID string) error {
	err := a.DB.C(cSpecialVisit, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID, "cancel": 0}, bson.M{"$set": bson.M{"deleted": time.Now().Unix(), "status": 2}})
	})
	if err != nil {
		return errors.Wrapf(err, "更新数据发生错误")
	}
	return nil
}

// Resend 更新重新发送的记录
func (a *SVisitDB) Resend(recordID string) error {
	err := a.DB.C(cSpecialVisit, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID, "cancel": 0}, bson.M{"$inc": bson.M{"message_frequency": 1}})
	})
	if err != nil {
		return errors.Wrapf(err, "更新短信发送次数发生错误")
	}
	return nil
}
